package com.biqee.job;

import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.biqee.exception.AccessBlockException;
import com.biqee.service.bq.BqTuanService;
import com.biqee.service.juhuasuan.JuHuaSuanParseService;
import com.biqee.util.EnvUtil;

public class JuHuaSuanTimeStatusParseJob extends QuartzJobBean {
	private static final Logger logger = Logger.getLogger(JuHuaSuanTimeParseJob.class);
	
	private boolean isRunning = false;
	
	// 2s
	private static final long SLEEP_INTERVAL = 2000;
	
	@Override
	protected void executeInternal(JobExecutionContext context)
			throws JobExecutionException {
		if(!EnvUtil.isTaskServer()) {
			logger.info("task not run because this server is not task server");
			return;
		}
		
		if(isRunning) {
			logger.info("skip parsing juhuasuan because isRunning is true.");
			return;
		}

		logger.info("start of parsing juhuasuan ");
		isRunning = true;
		try {
			JuHuaSuanParseService juHuaSuanParseService = (JuHuaSuanParseService)context.getJobDetail().getJobDataMap().get("juHuaSuanParseService");
			BqTuanService bqTuanService = (BqTuanService)context.getJobDetail().getJobDataMap().get("bqTuanService");
			List<String> itemIds = bqTuanService.listAllUnExpiredJuHuaSuanItemIds();
			for(String itemId : itemIds) {
				juHuaSuanParseService.parseStatusByItemId(itemId);
				Thread.sleep(SLEEP_INTERVAL);
			}
		} catch (AccessBlockException abe) {
			logger.error("taobao block us");
		} catch (Exception ex) {
			logger.error("parse failed! ", ex);
		}

		logger.info("end of parsing juhuasuan ");
		isRunning = false;
	}
	
}
